<template>
	<view class="csgo-case-battle">
		<navgats :images="img"></navgats>
		<!-- 顶部宝箱区域 -->
		<view class="cases-container">
			<scroll-view class="cases-scroll" scroll-x>
				<view class="cases-list">
					<view class="case-item" v-for="(arenaBox, index) in game_arena_box" :key="arenaBox.uniqueId"
						v-if="arenaBox.box && arenaBox.box.intact_cover" @click="showBoxRewards(arenaBox.box, index)">
						<image class="case-cover" :src="arenaBox.box.intact_cover" mode="widthFix" :lazy-load="true"
							:alt="arenaBox.box.name"></image>
						<view class="case-name">{{ arenaBox.box.name }}</view>
						<view class="case-price">
							<view class="icon">

							</view>
							<view class="text">
								{{ arenaBox.box.game_bean }}
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 房间信息 -->
		<view class="room-info">
			<view class="room-status">
				<text>对战结果</text>
			</view>
		</view>

		<!-- 玩家信息预览区域 -->
		<view class="players-preview">
			<view class="players-grid" :class="'grid-' + maxPlayers">
				<!-- 已加入的玩家 -->
				<view class="player-slot" v-for="i in maxPlayers" :key="i"
					:class="{ 'filled': players[i - 1], 'empty': !players[i - 1], 'winner': players[i - 1] && isPlayerWinner(i - 1) }">
					<template v-if="players[i - 1]">
						<image class="avatar" :src="players[i - 1].user.avatar" mode="widthFix"
							:alt="players[i - 1].user.name"></image>
						<view class="player-name">{{ players[i - 1].user.name }}</view>
						<view class="status joined">
							<view class="icon">

							</view>
							<view class="text">
								{{ getPlayerTotal(i - 1) }}
							</view>
						</view>
						<view class="winner-badge" v-if="isPlayerWinner(i - 1)">胜利</view>
					</template>
				</view>
			</view>
		</view>

		<!-- 对战结果：仅在已结束时展示 -->
		<view class="battle-result">
			<view class="player_item" v-for="(item, index) in players" :key="index" :class="{ 'winner': isPlayerWinner(index) }">
				<view class="title">
					{{ item.user.name }}
				</view>
				<view class="total_box">
					<view class="icon"></view>
					<view class="text">{{ getPlayerTotal(index) }}</view>
				</view>
				<view class="result_list">
					<view class="result_scroll_list">
						<view class="result_item" v-for="(items, indexs) in item.game_award" :key="indexs">
							<view class="imgbox">
								<view class="img"
									:style="{ backgroundImage: items.skins && items.skins.cover ? 'url(' + items.skins.cover + ')' : '' }">

								</view>
								<view class="name">
									{{ items.skins.name }}
								</view>
							</view>
							<view class="pricebox">
								<view class="icon">

								</view>
								<view class="text">
									{{ items.skins.bean }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 箱子奖励详情弹窗 -->
		<view class="reward-detail-modal" v-if="showRewardDetail">
			<view class="modal-overlay" @click="closeRewardDetail"></view>
			<view class="modal-content">
				<view class="modal-header">
					<text class="modal-title">{{ currentBoxDetail.name }} 包含的饰品</text>
					<button class="close-btn" @click="closeRewardDetail">×</button>
				</view>
				<view class="reward-list">
					<view class="reward-item" v-for="(item, index) in currentBoxDetail.contains" :key="index">
						<image :src="item.skins.cover" :alt="item.skins.name" mode="widthFix"></image>
						<view class="reward-info">
							<view class="reward-name">{{ item.skins.name }}</view>
							<view class="reward-dura">{{ item.skins.dura_alias }}</view>
							<view class="reward-value">{{ item.skins.bean }} 豆</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 错误提示 -->
		<view class="error-toast" v-if="errorMessage">
			<view class="toast-content">
				{{ errorMessage }}
				<button class="close-btn" @click="errorMessage = ''">确定</button>
			</view>
		</view>

		<!-- 加载中提示 -->
		<view class="loading" v-if="isLoading">
			<view class="loading-content">
				<view class="spinner"></view>
				<view class="loading-text">加载中...</view>
			</view>
		</view>
	</view>
</template>

<script>
import {
	getPKarenaDetail
} from "../../../api/pk/pk.js"
import navgats from "../../../Component/navgatsmy/navgatsmy.vue"
export default {
	data() {
		return {
			// 基础数据
			img: "https://img.jingkakeji.com/img/static/pks.png",
			roomId: "",
			errorMessage: "",
			isLoading: false,

			// 游戏数据
			game_arena_box: [],
			players: [],
			maxPlayers: 2,
			statusAlias: '',

			// 弹窗状态
			showRewardDetail: false,
			currentBoxDetail: null,
			selectedBoxIndex: -1
		};
	},
	components: {
		navgats
	},
	onLoad(option) {
		this.roomId = option.roomId
		// 进入页面立即调用接口获取玩家信息
		this.onpk(option.roomId)
	},
	methods: {
		// 获取对战详情
		async onpk(id) {
			try {
				this.isLoading = true
				const res = await getPKarenaDetail(id)
				// console.log(res);
				if (res.code === 200) {
					// 处理箱子数据，添加唯一标识
					this.game_arena_box = (res.data.game_arena_box || []).map((box, index) => ({
						...box,
						uniqueId: `${box.box?.id || ''}_${index}` // 生成唯一ID：箱子ID+索引
					}));

					// 保存状态
					this.statusAlias = res.data?.status_alias || '';

					// 从接口获取最大玩家数
					this.maxPlayers = res.data.user_num || 2;
					if (this.maxPlayers <= 2) this.maxPlayers = 2;
					if (this.maxPlayers >= 4) this.maxPlayers = 4;

					// 存储玩家数据并按座位号排序
					if (res.data.game_arena_player && res.data.game_arena_player.length) {
						this.players = [...res.data.game_arena_player].sort((a, b) => a.seat - b.seat)
					}
					// 结算：将失败者饰品转移给胜利者，并用于展示高亮
					this.handleSettlementMerge();
				} else {
					this.errorMessage = res.message || "获取对战信息失败"
				}
			} catch (error) {
				console.error("获取对战详情失败:", error)
				this.errorMessage = "网络错误，获取对战信息失败"
			} finally {
				this.isLoading = false
			}
		},

		// 获取玩家奖励列表（已结束）
		getPlayerAwards(playerIndex) {
			const player = this.players[playerIndex];
			if (!player || !Array.isArray(player.game_award)) {
				return [];
			}
			return player.game_award;
		},

		// 判断是否为平局
		isDraw() {
			if (!this.players || this.players.length < 2) return false;
			const totals = this.players.map((_, idx) => this.getPlayerTotal(idx));
			if (totals.length < 2) return false;
			const first = totals[0];
			return totals.every(t => Math.abs(t - first) < 0.01);
		},

		// 判断指定玩家是否胜利
		isPlayerWinner(playerIndex) {
			if (!this.players || !this.players[playerIndex] || this.isDraw()) return false;
			const me = this.getPlayerTotal(playerIndex);
			let maxOther = 0;
			for (let i = 0; i < this.players.length; i++) {
				if (i === playerIndex || !this.players[i]) continue;
				const t = this.getPlayerTotal(i);
				if (t > maxOther) maxOther = t;
			}
			return me > maxOther;
		},

		// 合并失败者饰品到胜者
		handleSettlementMerge() {
			if (!this.players || this.players.length === 0) return;
			// 仅在非平局时执行
			if (this.isDraw()) return;
			// 寻找胜者索引
			let winnerIndex = -1;
			for (let i = 0; i < this.players.length; i++) {
				if (this.isPlayerWinner(i)) {
					winnerIndex = i;
					break;
				}
			}
			if (winnerIndex === -1) return;
			// 将失败者 game_award 合并到胜者
			for (let i = 0; i < this.players.length; i++) {
				if (i === winnerIndex) continue;
				const loser = this.players[i];
				if (!loser) continue;
				const loserAwards = Array.isArray(loser.game_award) ? loser.game_award : [];
				if (loserAwards.length === 0) continue;
				const winner = this.players[winnerIndex];
				winner.game_award = (Array.isArray(winner.game_award) ? winner.game_award : []).concat(loserAwards);
				// 清空失败者列表以便 UI 正确显示
				loser.game_award = [];
			}
		},

		// 获取玩家总价值（豆）
		getPlayerTotal(playerIndex) {
			const awards = this.getPlayerAwards(playerIndex);
			const total = awards.reduce((sum, a) => {
				const bean = parseFloat(a?.skins?.bean || 0);
				return sum + (isNaN(bean) ? 0 : bean);
			}, 0);
			return Number(total.toFixed(2));
		},

		// 显示箱子奖励详情
		showBoxRewards(boxDetail, index) {
			this.currentBoxDetail = boxDetail;
			this.selectedBoxIndex = index;
			this.showRewardDetail = true;
		},

		// 关闭奖励详情弹窗
		closeRewardDetail() {
			this.showRewardDetail = false;
			this.currentBoxDetail = null;
			this.selectedBoxIndex = -1;
		}
	}
};
</script>

<style lang="scss" scoped>
.csgo-case-battle {
	background-color: #1a1a1a;
	color: #fff;
	height: 100vh;
	position: relative;
	background: url("https://img.jingkakeji.com/img/static/new_pks_pk/bg.png");
	background-repeat: no-repeat;
	background-position: center;
	background-size: cover;
	background-attachment: fixed;
	display: flex;
	flex-direction: column;
	align-items: center;
	overflow: hidden;

	/* 宝箱区域样式 */
	.cases-container {
		width: 100%;
		margin-bottom: 10rpx;

		.cases-scroll {
			width: 100%;
			white-space: nowrap;
			background-color: rgba(255, 255, 255, 0.3);

			.cases-list {
				display: inline-flex;
				padding: 10rpx 0;


				.case-item {
					width: 165rpx;
					height: 165rpx;
					display: inline-flex;
					margin-left: 20rpx;
					flex-direction: column;
					align-items: center;
					transition: all 0.3s ease;
					cursor: pointer;
					background-image: url("https://img.jingkakeji.com/img/static/new_pks_pk/item_bg.png");
					background-size: contain;
					background-position: center;
					background-repeat: no-repeat;

					&.active {
						box-shadow: 0 0 5rpx 5rpx white;
						border-radius: 20rpx;
					}

					&.opened {
						opacity: 0.7;
					}

					&.selected {
						box-shadow: 0 0 15rpx 5rpx #4cd964;
						border-radius: 10rpx;
					}

					.case-cover {
						width: 100rpx;
						height: 55rpx;
						border-radius: 10rpx;
					}

					.case-name {
						font-size: 24rpx;
						margin-top: 10rpx;
						text-align: center;
						white-space: normal;
						color: #31296A;
					}

					.case-price {
						width: 100%;
						height: 45rpx;
						font-size: 22rpx;
						text-align: center;
						line-height: 45rpx;
						color: #FBDC3B;
						margin-top: 10rpx;
						display: flex;
						align-items: center;
						justify-content: center;

						.icon {
							width: 20rpx;
							height: 20rpx;
							background-image: url("https://img.jingkakeji.com/img/static/new_pk/money.png");
							background-size: contain;
							background-position: center;
							background-repeat: no-repeat;
							margin-right: 10rpx;
						}
					}
				}
			}
		}
	}

	/* 房间信息 */
	.room-info {
		width: 95%;
		height: 80rpx;
		text-align: center;
		margin: 20rpx 0;
		background: url("https://img.jingkakeji.com/img/static/new_pks_pk/room_status_bg.png");
		background-repeat: no-repeat;
		background-position: center;
		background-size: contain;
		border-radius: 8rpx;
		line-height: 80rpx;

		.room-status {
			font-size: 26rpx;

			.status-text {
				color: #4cd964;
				font-weight: bold;
				margin-left: 10rpx;
			}
		}
	}

	/* 对战结果（静态展示） */
	.battle-result {
		width: 95%;
		height: 840rpx;
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-around;

		.player_item {
			width: 200rpx;
			height: 800rpx;
			border: 1rpx solid #ccc;
			border-radius: 20rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			&.winner {
				border-color: #4cd964;
				box-shadow: 0 0 18rpx 6rpx rgba(76, 217, 100, 0.5);
			}

			.title {
				width: 100%;
				height: 60rpx;
				background-color: #7869DA;
				font-size: 26rpx;
				text-align: center;
				line-height: 60rpx;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				border-radius: 20rpx 20rpx 0 0;
			}

			.total_box {
				width: 100%;
				height: 46rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-top: 8rpx;

				.icon {
					width: 22rpx;
					height: 22rpx;
					background-image: url("https://img.jingkakeji.com/img/static/new_pk/money.png");
					background-size: contain;
					background-position: center;
					background-repeat: no-repeat;
					margin-right: 8rpx;
				}

				.text {
					font-size: 24rpx;
					color: #FBDC3B;
				}
			}

			.result_list {
				width: 90%;
				height: 700rpx;
				margin-top: 20rpx;
				overflow-y: scroll;

				.result_scroll_list {
					width: 100%;
					display: flex;
					flex-direction: column;
					align-items: center;

					.result_item {
						width: 90%;
						height: 170rpx;
						margin-bottom: 20rpx;
						background-image: url("https://img.jingkakeji.com/img/static/new_pks_pk/item_bg.png");
						background-size: contain;
						background-position: center;
						background-repeat: no-repeat;

						.imgbox {
							width: 100%;
							height: 130rpx;
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: space-evenly;

							.img {
								width: 140rpx;
								height: 75rpx;
								background-size: contain;
								background-position: center;
								background-repeat: no-repeat;
							}

							.name {
								width: 100%;
								white-space: nowrap;
								overflow: hidden;
								text-overflow: ellipsis;
								font-size: 22rpx;
								color: #31296A;
								text-indent: 20rpx;
							}
						}

						.pricebox {
							width: 100%;
							height: 40rpx;
							display: flex;
							align-items: center;
							justify-content: center;

							.icon {
								width: 20rpx;
								height: 20rpx;
								background-image: url("https://img.jingkakeji.com/img/static/new_pk/money.png");
								background-size: contain;
								background-position: center;
								background-repeat: no-repeat;
								margin-right: 10rpx;
							}

							.text {
								font-size: 22rpx;
								color: #FBDC3B;
							}
						}
					}
				}
			}
		}
	}

	/* 玩家预览区域 - 战斗未开始时 */
	.players-preview {
		width: 95%;
		margin: 30rpx 0;

		.players-grid {
			width: 100%;
			height: 220rpx;
			border-radius: 10rpx;
			display: flex;
			justify-content: space-evenly;

			.player-slot {
				width: 220rpx;
				height: 220rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				border-radius: 8rpx;
				transition: all 0.3s ease;
				background-image: url("https://img.jingkakeji.com/img/static/new_pks_pk/user_bg.png");
				background-size: contain;
				background-position: center;
				background-repeat: no-repeat;

				&.winner {
					box-shadow: 0 0 18rpx 6rpx #4cd964;
					transform: translateY(-4rpx);
				}

				.avatar,
				.avatar-placeholder {
					width: 80rpx;
					height: 80rpx;
				}

				.avatar {
					border: 2rpx solid white;
				}

				.avatar-placeholder {
					display: flex;
					justify-content: center;
					align-items: center;
					background-color: #7869da;
					border: 1px solid white;

					.add-icon {
						font-size: 40rpx;
						color: white;
					}
				}

				.player-name {
					margin-top: 15rpx;
					font-size: 26rpx;
					text-align: center;
					max-width: 100%;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.status {
					margin-top: 8rpx;
					font-size: 22rpx;
					padding: 3rpx 15rpx;
					border-radius: 12rpx;
					display: flex;
					align-items: center;

					.icon {
						width: 20rpx;
						height: 20rpx;
						background-image: url("https://img.jingkakeji.com/img/static/new_pk/money.png");
						background-size: contain;
						background-position: center;
						background-repeat: no-repeat;
						margin-right: 10rpx;
					}

					.text {
						color: #FBDC3B;
					}

					&.joined {
						color: #4cd964;
						background-color: rgba(0, 0, 0, 0.3);
					}

					&.waiting {
						color: red;
						background-color: rgba(0, 0, 0, 0.3);
					}
				}

				.winner-badge {
					margin-top: 8rpx;
					padding: 2rpx 10rpx;
					background: #4cd964;
					color: #111;
					border-radius: 20rpx;
					font-size: 20rpx;
					font-weight: 700;
				}
			}
		}
	}


	/* 奖励详情弹窗样式 */
	.reward-detail-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;

		.modal-overlay {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(0, 0, 0, 0.7);
		}

		.modal-content {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			width: 90%;
			max-height: 80vh;
			background-color: #1a1a1a;
			border-radius: 15rpx;
			overflow: hidden;

			.modal-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx;
				background-color: #333;

				.modal-title {
					font-size: 28rpx;
					font-weight: bold;
				}

				.close-btn {
					width: 60rpx;
					height: 60rpx;
					line-height: 60rpx;
					text-align: center;
					background-color: transparent;
					color: #fff;
					font-size: 36rpx;
					padding: 0;
					border: none;
				}
			}

			.reward-list {
				padding: 20rpx;
				max-height: calc(80vh - 100rpx);
				overflow-y: auto;
				background-color: #D8D3FB;

				.reward-item {
					display: flex;
					padding: 15rpx 0;
					border-bottom: 1px solid rgba(255, 255, 255, 0.1);

					image {
						width: 100rpx;
						height: 100rpx;
						border-radius: 5rpx;
					}

					.reward-info {
						margin-left: 20rpx;
						flex: 1;

						.reward-name {
							font-size: 26rpx;
						}

						.reward-dura {
							font-size: 22rpx;
							color: #999;
							margin-top: 5rpx;
						}

						.reward-value {
							font-size: 24rpx;
							color: #00ff00;
							margin-top: 5rpx;
						}
					}
				}
			}
		}
	}

	/* 错误提示样式 */
	.error-toast {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 1000;

		.toast-content {
			background-color: rgba(0, 0, 0, 0.8);
			padding: 30rpx;
			border-radius: 10rpx;
			font-size: 28rpx;
			text-align: center;

			.close-btn {
				margin-top: 20rpx;
				background-color: #ff3300;
				color: #fff;
				border: none;
				padding: 10rpx 30rpx;
				border-radius: 5rpx;
				font-size: 26rpx;
			}
		}
	}

	/* 加载中样式 */
	.loading {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;

		.loading-content {
			display: flex;
			flex-direction: column;
			align-items: center;

			.spinner {
				width: 60rpx;
				height: 60rpx;
				border: 5rpx solid rgba(255, 255, 255, 0.3);
				border-radius: 50%;
				border-top-color: #fff;
				animation: spin 1s ease-in-out infinite;
			}

			.loading-text {
				margin-top: 20rpx;
				font-size: 28rpx;
				color: #fff;
			}
		}
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}

}
</style>